<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2024/10/10
 * Time: 下午4:36
 */

namespace app\api\controller\v50;

use app\aliyun\controller\AliyunFilterWordV2;
use app\api\controller\v2\Auth;
use app\common\cachemodel\AppConfig;
use app\common\cachemodel\chat\HzChatRecord;
use app\common\cachemodel\chat\HzChatRecordDetails;
use app\common\lib\tarot\Tarot;
use app\common\lib\Util;
use think\Log;

class UserAiChat extends Auth
{

    /**
     * 塔罗提问内容安全验证
     * @return \think\response\Json
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function verifyTarotQuestion()
    {
        $question = input('question/s');
        $aliRes = AliyunFilterWordV2::checkAIText($question, 'llm_query_moderation_02');
        if ($aliRes['status'] === false)
        {
            return show(config('code.error'), $aliRes['msg']);
        }
        return show(config('code.success'), '请求成功');
    }

    /**
     * Ai会话塔罗占卜提问
     * @return \think\response\Json
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function submitTarotQuestion()
    {
        $question = input('question/s');
        $rid = input('rid/d', 0);
        $gptModel = input('model/s', '');
        $typeId = input('type_id/d', 0);

        $aliRes = AliyunFilterWordV2::checkAIText($question, 'llm_query_moderation_02');
        if ($aliRes['status'] === false)
        {
            return show(config('code.error'), $aliRes['msg']);
        }
        $hzChatRecordModel = new HzChatRecord();
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);

        // 通过rid 取当前会话ID
        if ($rid)
        {
            $chatId = $hzChatRecordModel->getChatIdByRid($rid);
        } else
        {
            $chatId = $hzChatRecordModel->getChatIdByUid($this->user['id']);
        }
        if (!$chatId)
        {
            return show(config('code.error'), '服务异常，请刷新页面重试～');
        }
        $nowTimw = $this->request->time();
        try
        {
            if (Util::isOnline())
            {   // 线上环境
                $chatConfig = (new AppConfig())->configInfo('chat_config');
                $gptModel = $chatConfig['gpt_model_name'] ?? '';
            }
            //  塔罗牌阵 信息
            $tarotConfig = config('tarot');
            $tarotTypeInfo = $tarotConfig['tarot_type'][$typeId];
            $tarotModel = new Tarot();
            $cardList = $tarotModel->getTarotCard($tarotTypeInfo, 1);
            $tarotCardsInfo = $tarotModel->getTarotInfo($tarotConfig, $cardList, $typeId, $numData['res_num']);
            $unlockNum = $tarotModel->getGetTarotTypeUnlockDecNum($typeId);
            $tarotCardsShort = [];
            foreach ($tarotCardsInfo as $item)
            {
                $tarotCardsShort[] = [
                    'card_id' => $item['card_id'],
                    'direction' => $item['direction'],
                    'name' => $item['name'],
                ];
            }
            $extend = [
                'result_type' => 2,
                'model_name' => $gptModel,
                'is_valid' => 1,
                'stream' => 1,
                'sas' => 3, // 语义解析集群分类场景结果 0为专业场景，1为基础场景，2为拒答场景 3未进行语义解析之间进行骰子获取结果
                'sact' => [],
                'dice_info' => null,
                'tarot_info' => [
                    'tarot_cards' => $tarotCardsShort,
                    'tarot_type' => $typeId,
                    'tarot_name' => $tarotConfig['tarot_type_name'][$typeId],
                    'status' => 2,
                    'answer_content' => '',
                    'unlock_num' => $unlockNum,
                    'btn_name' => "消耗{$unlockNum}次解读牌阵",
                    'question' => $question,
                ],
            ];
            $insertData = [
                [    // 塔罗结果信息
                    'chat_id' => $chatId,
                    'uid' => $this->user['id'],
                    'rid' => $rid,
                    'type' => 1,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => $question, // 提问问题
                    'data_type' => 3,   // 1=>普通消息  2=>结果消息 3=>扩展消息'
                    'extend' => $extend,  //  澄清数据
                    'result_data' => '',
                    'option_id' => '',
                    'num_type' => 0, // 使用类型 1=免费次数 2=>vip次数 3=>购买次数 4=>赠送次数
                    'pid' => 0, // 待更新
                    'create_time' => $nowTimw,
                ],
            ];
            $resInsertData = $hzChatRecordDetailsModel->SaveData($chatId, $insertData);
            $resData = $hzChatRecordDetailsModel->dataListResert($resInsertData, true);
            $resData[0]['create_time'] = '';
            $resData[0]['stream'] = 0;
            $resData[0]['is_stream_reload'] = 0;
            $btnName = "消耗{$unlockNum}次解读牌阵";
            if ($numData['res_num'])
            {
                $btnName .= "({$numData['res_num']}次)";
            }
            return show(config('code.success'), '请求成功', [
                'num' => $numData['res_num'],
                'input_text' => $hzChatRecordDetailsModel->getInputPlaceholder($numData),
                'list' => $resData,
                'tarot_data' => [
                    'tarot_cards' => $tarotCardsInfo,
                    'btn_name' => $btnName,
                    'unlock_num' => $unlockNum,
                    'chat_id' => $resData[0]['chat_id'],
                ],
            ]);
        }
        catch (\Exception $e)
        {
            Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 解锁AI会话 塔罗提问
     * @return \think\response\Json
     * @throws \Exception
     */
    public function unlockTarot()
    {
        $chatDetailId = input('chat_id/d', 0);
        $hzChatRecordDetailsModel = new HzChatRecordDetails();
        $detail = $hzChatRecordDetailsModel->getInfoById($chatDetailId);
        $resData = $hzChatRecordDetailsModel->dataListResert([$detail], true);
        $resData[0]['create_time'] = '';
        $resData[0]['stream'] = 1; // 前端是否展示流式效果
        $resData[0]['is_stream_reload'] = 0;// 是否需要请求重新加载流式数据
        $resData[0]['tarot_info']['status'] = 1;
        $resData[0]['tarot_info']['answer_content'] = '';

        $numData = $hzChatRecordDetailsModel->getChatQueryEndNumRes($this->user['id']);
        if ($detail['extend']['tarot_info']['status'] == 2)
        {
            if ($numData['res_num'] <= 0)
            {   // 会话次数 用尽
                $msg = $numData['vip_level'] > 0 ? '今日提问机会用尽，明天再来吧～' : '提问机会用尽，请开通会员或购买';
                return show(config('code.error'), $msg);
            }
            $decNum = (new Tarot())->getGetTarotTypeUnlockDecNum($detail['extend']['tarot_info']['tarot_type']);
            // 扣除次数
            $numData = $hzChatRecordDetailsModel->chatQueryEndNumDec($this->user['id'], $numData, $decNum);

            //更新数据状态
            $detail['extend']['tarot_info']['status'] = 1;
            $hzChatRecordDetailsModel->UpdateData($chatDetailId, ['extend' => json_encode($detail['extend'], JSON_UNESCAPED_UNICODE)]);

        }
        return show(config('code.success'), '请求成功', [
            'num' => $numData['res_num'],
            'input_text' => $hzChatRecordDetailsModel->getInputPlaceholder($numData),
            'list' => $resData,
        ]);
    }
}
